package com.rd.sys.action.login;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import baseproj.common.exception.BaseServiceException;

import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.rd.sys.action.BaseAction;
import com.rd.sys.common.base.CommonConstants;
import com.rd.sys.common.web.session.SessionUtil;
import com.rd.sys.dto.sys.user.UserInfoDto;
import com.rd.sys.dto.sys.user.UserLoginDto;
import com.rd.sys.service.sys.user.UserLoginService;
import com.rd.sys.service.sys.user.impl.UserLoginServiceException;

public class LoginAction extends BaseAction {
    private static final long serialVersionUID = -2803824514450597999L;

    private UserInfoDto userInfo;
    private UserLoginDto loginInfo;

    @Autowired
    private UserLoginService userLoginService;

    @InputConfig(resultName = "login")
    public String login() {
        try {
            userInfo = userLoginService.loginPortal(loginInfo, request);

            // 把用户信息保存到session中
            SessionUtil.createSession(request, CommonConstants.UserConstats.USER_SESSION_FLAG, userInfo);
        } catch (BaseServiceException be) {
            if (be.getErroCode() == UserLoginServiceException.ACCOUNT_OR_PASSWORD_ERROR) {
                this.addFieldError("loginInfo.accountOrPassword", be.getErroDesc());
            } else if (be.getErroCode() == UserLoginServiceException.LOGIN_VALIDCODE_INVALID) {
                this.addFieldError("loginInfo.validcode", be.getErroDesc());
            }
            return "login";
        } catch (Exception e) {
            return "login";
        }
        return "index";
    }

    public String logout() throws Exception {
        HttpSession session = SessionUtil.getSession(request);
        if (session != null) {
            session.invalidate();
        }
        return "login";
    }

    public UserInfoDto getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfoDto userInfo) {
        this.userInfo = userInfo;
    }

    public UserLoginDto getLoginInfo() {
        return loginInfo;
    }

    public void setLoginInfo(UserLoginDto loginInfo) {
        this.loginInfo = loginInfo;
    }

}
